<?php

namespace App\Http\Controllers\Api;


use App\Models\Member;
use App\Models\Sms;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\Validate\api\UserValidate;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;


class LoginController extends BaseController
{
    public $successStatus=200;
    protected $Member;
    protected $Sms;
    protected $v;
    /**
     * api注册
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     */

    public function __construct(Member $Member,Sms $Sms,UserValidate $userValidate)
    {
        $this->Member = $Member;
        $this->Sms = $Sms;
        $this->v = $userValidate;
    }


    public function register(Request $request){
        $this->v->validate('register');
        $data=$request->input();
        $phone = $data['phone'];


        $verifycode = $data['verifycode'];

        //check $phone  $verifycode
        if(!$this->Sms->checkCode($verifycode,$phone,1)){
            return ['code'=>0,'msg'=>'验证码错误或已到期'];
        }

        if ($this->Member->checkPhone($phone)){
            //返回错误信息
            return ['code'=>0,'msg'=>'手机号已注册'];
        }

        $rs =$this->Member->create([
                'phone'=> $phone,
                'password'=> bcrypt($data['password']),
                'nickname'=>$phone,

            ]);
        if ($rs ){
            return response()->json(['code'=>1,'msg'=>'恭喜您,注册成功']);
        }else{
            return response()->json(['code'=>0,'msg'=>'注册失败']);
        }
    }

    /**
     * api登录
     * @param Request $request
     * @return \Illuminate\Http\Js onResponse
     */
    public function doLogin(Request $request){
        $this->v->validate('login');

        if(Auth::guard('member')->attempt(['phone'=>$request->phone,'password'=>$request->pwd])){

            $rs = $this->Member->where(['phone'=>$request->phone])->value('enabled');
            if ($rs==1){
                return response()->json(['code'=>0,'msg'=>'您已经被禁止登陆。请规范使用']);
            }

            $ip = $_SERVER['REMOTE_ADDR'];
            $time = date('Y-m-d H:i:s');
            $this->Member->where(['phone'=>$request->phone])->update(['last_login_ip'=>$ip,'last_login_time'=>$time]);

            $user = Auth::guard('member')->user();

            $success['token'] =  $user->createToken('cartoon-api')->accessToken;
            $success['token_type'] = 'Bearer';
            return response()->json(['code'=>1,'data' => $success,'TOKEN_CYCLE'=>env('TOKEN_CYCLE',15)*24*60*60]);
        } else{
            return response()->json(['code'=>0,'msg'=>'账号或密码错误，请重新输入。']);
        }

    }

    /**
     * api获取用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDetails(Request $request)
    {

        $id = Auth::guard('api')->user()->member_id;

        $user = $this->Member->shows($id);
        return response()->json(['code'=>1,'data' => $user], $this->successStatus);
    }


    /**
     * 退出登录
     * @param Request $request
     */
    public function loginout(){
        if (Auth::guard('api')->check()) {
            Auth::guard('api')->user()->token()->delete();
        }
        return response()->json(['msg' => '退出成功', 'status_code' => 1, 'data' => null]);
    }

    public function sendSms(Request $request){
        $this->v->validate('sendSms');
        $data=$request->input();
        $code=rand_code(1,6);
        $msg='【xxx】短信登录验证码：'.$code.'(5分钟内有效)';

        $post=sendSMS($data['phone'],$msg);
        $total = json_decode((string)$post->getBody(), true);
        if($total['status']=='success'){
            $this->Sms->create(
                [
                    'type'=>1,
                    'code'=>$code,
                    'phone'=>$data['phone'],
                    'expire_time'=>date('Y-m-d H:i:s',time()+300),
                    'create_time'=>date('Y-m-d H:i:s'),
                ]
            );
            return response()->json(['code'=>1,'msg'=>'发送成功。']);
        }else{
            return response()->json(['code'=>0,'msg'=>'发送失败。']);
        }
    }

}
